package chapter1;

import lombok.extern.slf4j.Slf4j;

/**
 * @author caiya
 * @date 2020/3/12 21:43
 */
@Slf4j
public class ThreadSleepTest {
    private static final Object obj = new Object();

    public static void main(String[] args) {
        /**
         * 1、说明Thread.sleep在休眠期间，持有的监视器锁并不会释放，只是单纯不参与CPU调度
         * 2、因调用sleep使得线程休眠期间，被其它线程interrupt的话，那么在sleep方法处抛出InterruptedException
         */

        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (obj) {
                    try {
                        log.debug("threadA begin sleep...");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.debug("threadA end sleep...");
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("threadB wait for the lock...");
                synchronized (obj) {
                    try {
                        log.debug("threadB begin sleep...");
                        Thread.sleep(4000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.debug("threadB end sleep...");
                    log.debug("threadB running...");
                }
            }
        });

        threadA.start();
        threadB.start();

        try {
            Thread.sleep(50);
            threadA.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
